package board;

import java.io.File;
import java.sql.PreparedStatement;
import java.util.ArrayList;










import member.MemberVo;

import org.apache.ibatis.session.SqlSession;

import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;

public class BoardMyba {

	private SqlSession session;  // 커넥션 객체가 생성된 상태
	BoardVo boardVo;

	int fileSize = 10*1024*1024;
	String uploadPath = "C:\\kjm_1403\\web1403\\WebContent\\MyHome\\board_mybatis\\upload";
	String fileEncoding = "utf-8";

	// 페이지분리 관련된 필드
	int listSize = 3; // 한페이지에 보여질 행수
	int blockSize = 2; // 보여질 페이지 이동 번호 수

	int totSize = 0; // 검색된 데이터 총 갯수
	int totPage = 1; // 전체 페이지 수
	int totBlock = 1; // 전체 블럭수

	int nowPage = 1; // 현제 페이지
	int nowBlock = 1; // 현재 블럭

	int startNo = 1; // 목록의 시작 위치
	int endNo = 3; // 목록의 끝 위치
	int startPage = 1; // 현재 블럭의 시작 페이지번호
	int endPage = 2; //현재블럭의 끝페이지 번호


	public BoardMyba(){
		try{
			// session 을 통해서 mapper를 호출한다?!
			session = BoardFactory.getFactory().openSession();

		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
	public void computePage(){
		totPage = (int)Math.ceil(totSize*1.0/listSize);
		totBlock = (int)Math.ceil(totPage*1.0/blockSize);

		nowBlock = (int)Math.ceil(nowPage*1.0/blockSize);

		endPage = nowBlock*blockSize;
		startPage = endPage - blockSize+1;
		if(totPage < endPage){
			endPage = totPage;
		}
		endNo = nowPage * listSize;
		startNo = endNo - listSize + 1;
		if(totSize < endNo) endNo = totSize;

		boardVo.setStartNo(startNo);
		boardVo.setEndNo(endNo);

	}

	public BoardVo view(){
		BoardVo vo = null;
		int hit = 0;
		try{
			hit = (Integer)session.update("board.hit", boardVo);
			if(hit>0) session.commit();
			else session.rollback();

			boardVo.setHit(hit);

			vo = (BoardVo)session.selectOne("board.view", boardVo.getSerial());
			session.close();

		}catch(Exception ex){
			ex.printStackTrace();
		}

		return vo;
	}


	public ArrayList<BoardVo> list(){
		ArrayList<BoardVo> data = null;
		try{
			totSize = (Integer)session.selectOne("board.cnt", boardVo);

			computePage();

			data = (ArrayList<BoardVo>)session.selectList("board.list", boardVo);
			session.close();
		}catch(Exception e){
			e.printStackTrace();
		}

		return data;
	}

	public boolean insert(){
		boolean flag=false;

		try{
			MultipartRequest mr = new MultipartRequest(
					boardVo.getRequest(),
					uploadPath,
					fileSize, 
					fileEncoding, 
					new DefaultFileRenamePolicy()
					);


			String mid = mr.getParameter("mid");
			String subject = mr.getParameter("subject");
			String content = mr.getParameter("content");
			String pwd = mr.getParameter("pwd");
			String filename = mr.getParameter("filename");
			String part = mr.getParameter("part");
			
			String sysfile = mr.getFilesystemName("newfilename");
			String orifile = mr.getOriginalFileName("filename");
			String fileDelFlag = mr.getParameter("fileDelFlag");

			BoardVo v = new BoardVo();
			v.setMid(mid);
			v.setSubject(subject);
			v.setContent(content);
			v.setPwd(pwd);
			v.setPart(part);
			v.setFilename(filename);
			
			
			//DB저장
			int cnt = session.insert("board.insert", v);
			if(cnt >0) {
				session.commit();
				flag = true;
			}else{
				session.rollback();
				flag = false;
			}
			
			
			
/*			v = new BoardVo();
			v.setPart(part);
			v.setFilename(sysfile);
			
			if(sysfile != null){
				cnt = session.insert("board.insert_file", sysfile);
				if(cnt > 0) {
					session.commit();
					flag=true;
				}
				else {
					session.rollback();
					flag=false;
				}
			}
*/

			
			session.close();
		}catch(Exception e){
			e.printStackTrace();
		}
		return flag;
		
	}
	
	
	public boolean repinsert(){
		boolean flag= false;

		try{
			MultipartRequest mr = new MultipartRequest(
					boardVo.getRequest(),
					uploadPath,
					fileSize, 
					fileEncoding, 
					new DefaultFileRenamePolicy()
					);

			String mid = mr.getParameter("mid");
			String subject = mr.getParameter("subject");
			String content = mr.getParameter("content");
			String pwd = mr.getParameter("pwd");
			String part = mr.getParameter("part");
			
			int grp = Integer.parseInt(mr.getParameter("grp"));
			String deep = mr.getParameter("deep");
			
			String sysfile = mr.getFilesystemName("newfilename");
			String orifile = mr.getOriginalFileName("filename");

			String fileDelFlag = mr.getParameter("fileDelFlag");
			
			// mabatis에 parameter를 던지기 위한 작업
			BoardVo v = new BoardVo();
			v.setMid(mid);
			v.setSubject(subject);
			v.setContent(content);
			v.setPwd(pwd);
			v.setPart(part);
			v.setFilename(sysfile);
			v.setGrp(grp);
			v.setDeep(deep);
			
			int cnt = session.insert("board.repinsert", v);
			
			if(cnt >0) {
				session.commit();
				flag = true;
			}else{
				session.rollback();
				flag = false;
			}

			
			session.close();

		}catch(Exception e){
			e.printStackTrace();
		}
		return flag;
	}


	public boolean modify(){
		boolean flag= false;
		try{

			MultipartRequest mr = new MultipartRequest(
					boardVo.getRequest(),
					uploadPath,
					fileSize, 
					fileEncoding, 
					new DefaultFileRenamePolicy()
					);

			/*			복잡해 보이는 방법은 주석처리/ 가능하긴 하다		

  			boardVo.setPart(mr.getParameter("part"));
			boardVo.setMid(mr.getParameter("mid"));
			boardVo.setPwd(mr.getParameter("pwd"));
			boardVo.setSubject(mr.getParameter("subject"));
			boardVo.setContent(mr.getParameter("content"));
			boardVo.setSerial(Integer.parseInt(mr.getParameter("serial")));
			boardVo.setFilename(mr.getFilesystemName("filename"));
			 */

			String mid = mr.getParameter("mid");
			String subject = mr.getParameter("subject");
			String content = mr.getParameter("content");
			String pwd = mr.getParameter("pwd");
			String filename = mr.getParameter("filename");
			String sysfile = mr.getFilesystemName("newfilename");
			String orifile = mr.getOriginalFileName("filename");
			int serial = Integer.parseInt(mr.getParameter("serial"));
			String fileDelFlag = mr.getParameter("fileDelFlag");

			// mabatis에 parameter를 던지기 위한 작업
			BoardVo v = new BoardVo();
			v.setMid(mid);
			v.setSubject(subject);
			v.setContent(content);
			v.setPwd(pwd);
			v.setFilename(filename);
			v.setSerial(serial);

			// 기존 첨부된 파일을 삭제
			if(fileDelFlag.equals("del")){
				FileDel(filename, serial);
			}


			int cnt = session.update("board.update", v);
			session.commit();

			if(cnt >0) flag = true;

			v = new BoardVo();
			v.setFilename(sysfile);
			v.setFileid(serial);

			System.out.println("sysfile" + sysfile);
			System.out.println("serial:" + serial);


			//새로운 첨부파일이 생성된 경우(내용+첨부파일이 모두 수정된 경우)

			if(sysfile != null && sysfile != ""){
				cnt = session.insert("board.update_file", v);
				if(cnt > 0) {
					session.commit();
					flag = true;
				}
				else {
					session.rollback();
					flag = false;
				}
			}

			session.close();
		}catch(Exception e){
			e.printStackTrace();
		}
		return flag;
	}
	
	public void FileDel(String oldfile, int serial){

		try{

			int cnt = session.delete("board.fileDel", boardVo);

			session.commit();

			File file = new File(uploadPath + "/" + oldfile);
			if(file.exists()) file.delete();



		}catch(Exception e){
			e.printStackTrace();
		}
	}
	public boolean delete(){
		boolean flag = false;

		try{
			int cnt = session.delete("board.delete", boardVo);
			
			if(cnt > 0) flag = true;
			if(boardVo.getFilename()!= null && !boardVo.getFilename().equals("")){
				File file = new File(uploadPath + "/" + boardVo.getFilename());
				if(file.exists()) file.delete();
				
				int cnt2 = session.delete("board.fileDel", boardVo);
				if(cnt2 > 0) flag = true;
			}
			
			if(flag) session.commit();
			else session.rollback();

			session.close();
		}catch(Exception e){
			e.printStackTrace();
		}
		return flag;
	}


	public BoardVo getBoardVo() {
		return boardVo;
	}

	public void setBoardVo(BoardVo boardVo) {
		this.boardVo = boardVo;
	}


	public String getUploadPath() {
		return uploadPath;
	}

	public int getListSize() {
		return listSize;
	}

	public void setListSize(int listSize) {
		this.listSize = listSize;
	}

	public int getBlockSize() {
		return blockSize;
	}

	public void setBlockSize(int blockSize) {
		this.blockSize = blockSize;
	}

	public int getTotSize() {
		return totSize;
	}

	public void setTotSize(int totSize) {
		this.totSize = totSize;
	}

	public int getTotPage() {
		return totPage;
	}

	public void setTotPage(int totPage) {
		this.totPage = totPage;
	}

	public int getTotBlock() {
		return totBlock;
	}

	public void setTotBlock(int totBlock) {
		this.totBlock = totBlock;
	}

	public int getNowPage() {
		return nowPage;
	}

	public void setNowPage(int nowPage) {
		this.nowPage = nowPage;
	}

	public int getNowBlock() {
		return nowBlock;
	}

	public void setNowBlock(int nowBlock) {
		this.nowBlock = nowBlock;
	}

	public int getStartNo() {
		return startNo;
	}

	public void setStartNo(int startNo) {
		this.startNo = startNo;
	}

	public int getEndNo() {
		return endNo;
	}

	public void setEndNo(int endNo) {
		this.endNo = endNo;
	}

	public int getStartPage() {
		return startPage;
	}

	public void setStartPage(int startPage) {
		this.startPage = startPage;
	}

	public int getEndPage() {
		return endPage;
	}

	public void setEndPage(int endPage) {
		this.endPage = endPage;
	}



}
